import config from "@/config"
import cookies from 'js-cookie'
export class FetchService {
    private requestInterceptors: Array<(url: string, options: RequestInit) => void> = [];
    private responseInterceptors: Array<(response: Response) => void> = [];
    async get<T>(url: string,data:any): Promise<T> {
      return this._request('GET', url,data);
    }
   
    async post<T>(url: string, body: any): Promise<T> {
      return this._request('POST', url, body);
    }
   
    async put<T>(url: string, body: any): Promise<T> {
      return this._request('PUT', url, body);
    }
   
    async delete<T>(url: string): Promise<T> {
      return this._request('DELETE', url);
    }
   
    addRequestInterceptor(interceptor: (url: string, options: RequestInit) => void) {
      this.requestInterceptors.push(interceptor);
    }
   
    addResponseInterceptor(interceptor: (response: Response) => void) {
      this.responseInterceptors.push(interceptor);
    }
   
    private async _request<T>(method: string, url: string, body?: any): Promise<T> {
      let _url = config.baseUrl+url;
      let options: RequestInit = {
        method: method,
        headers: {
          'Content-Type': 'application/json'
        }
      };
      if (body) {
        if (method === 'GET') {
          if(Object.keys(body).length > 0) {
            _url += `?${new URLSearchParams(body)}`;
          }
          //_url += `?${new URLSearchParams(body)}`;
        }else{
          options.body = JSON.stringify(body);
        } 
        
      }
      this.runRequestInterceptors(_url, options);
      const response = await fetch(_url, options);
      this.runResponseInterceptors(response);
      if (!response.ok) {
        throw new Error(response.statusText);
      }
      const data: T = await response.json();
      return data;
    }
   
    private runRequestInterceptors(_url: string, options: RequestInit) {
      if (!options.headers) {
        options.headers = {
          authorization:""
        };
      }
      options.headers["authorization" as keyof typeof options.headers] = cookies.get('token'); 
      //options.headers.authorization = cookies.get('token');
      this.requestInterceptors.forEach(interceptor => interceptor(_url, options));
    }
   
    private runResponseInterceptors(response: Response) {
      this.responseInterceptors.forEach(interceptor => interceptor(response));
    }
  }